package com.malou.server.ventas.tarjeta;

import java.sql.SQLException;
import java.util.List;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.malou.client.ventas.tarjeta.Tarjeta;
import com.malou.server.base.Conexion;
import com.malou.server.base.util.GxtGridPaginate;

public class Tarjetas {

	private static SqlMapClient sqlMap = null;
	public static Integer errorTipo = 0;
	
	@SuppressWarnings("unchecked")
	public static PagingLoadResult<Tarjeta> getPaginate(GxtGridPaginate paginate){		     
		
		sqlMap = Conexion.getSqlMap();
		paginate.setLimit();
		if(paginate.order.equals("")){
			paginate.order = " order by id desc";
		}
		List<Tarjeta> data = null;
		try {
			data = sqlMap.queryForList("paginateTarjeta", paginate);				
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return new BasePagingLoadResult<Tarjeta>(data, paginate.offset, count(paginate));
	}
	
	public static Integer count(GxtGridPaginate paginate){
		Integer count = null;
		try {
			count = (Integer) sqlMap.queryForObject("countTarjeta", paginate);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return count;
	}
	
	public static boolean save(Tarjeta tj){
		boolean retorno = true;		 
	
		sqlMap = Conexion.getSqlMap();
		try {
			if(isValid(tj)){
				if(tj.getId() != null)
					sqlMap.update("updateTarjeta", tj);
				else			
					sqlMap.insert("insertTarjeta", tj);
			}else
				retorno = false;
		} catch (SQLException e) {
			retorno = false;
			e.printStackTrace();			
		}
		return retorno;
	}
	
	public static boolean delete(Integer id){
		boolean retorno = true;		 
		
		sqlMap = Conexion.getSqlMap();
		try {
			if(id != null)
				sqlMap.delete("deleteTarjeta", id);
			else
				retorno = false;
		} catch (SQLException e) {
			retorno = false;
			e.printStackTrace();			
		}
		return retorno;
	}
	
	public static boolean deleteAll(String ids){
		boolean retorno = true;		   
		
		sqlMap = Conexion.getSqlMap();
		try {
			if(!ids.equals(""))
				sqlMap.delete("deleteTarjetas", ids);
			else
				retorno = false;
		} catch (SQLException e) {
			retorno = false;
			e.printStackTrace();			
		}
		return retorno;
	}
	
	private static boolean isValid(Tarjeta tj){
		boolean retorno = true;
        Integer cant;
        try {
	        if(tj.getDescripcion()!= null){
	         cant = (Integer)sqlMap.queryForObject("validaDescripcionTarjeta", tj);
	             if(cant != 0){
	            	errorTipo = 1; //Ya existe esta tarjeta;
	                retorno = false;
	            }
	        }	        
        } catch (SQLException e) {
			retorno = false;
			e.printStackTrace();			
		}
        return retorno;
	}
}
